<template>
  <BasicForm @register="registerForm" >
    <template #spec="{ model, field, schema }">
      <a-row :gutter="8">
        <a-col :sm="24" :md="24" :lg="24" :xl="24" class="goods-spec-type">
          <a-radio-group v-model:value="model[field]" :disabled="schema.dynamicDisabled">
            <a-radio :value="true">多规格</a-radio>
            <a-radio :value="false">统一规格</a-radio>
          </a-radio-group>
        </a-col>
        <a-col :sm="24" :md="24" :lg="24" :xl="24">
          <MyCardGroup v-model:value="state.specList" width="96%" v-if="model[field] === true" style="margin-top: 10px;"
            :minCardNumber="0" addCardButtonName="添加规格" :isInitOne="false"
            :showDelete="!schema.dynamicDisabled"
            :showAddCardButton="!schema.dynamicDisabled"
            :defaultData="specCardDefaultData" :beforeAdd="handleBeforeAddSpec"
            delete-title="删除此规格将丢失本次编辑内容, 是否删除?" :before-delete="handleBeforeDeleteSpec"
            @remove="handleRemoveCardGroup">
            <template v-slot="{ data }">
              <SelectSpec :spec="data" :is-update="state.isUpdate" :sku-list="state.skuList"  @change="handleSelectSpec"/>
            </template>
          </MyCardGroup>
          <a-form-item-rest v-else>
            <!-- 统一规格 -->
            <a-input 
              v-model:value="state.singleSpecValue"
              placeholder="例如: 50ml"
            />
          </a-form-item-rest>

        </a-col>
      </a-row>
    </template>

    <template #linePrice="{ model, field, schema }">
      <InputNumber 
        :disabled="schema.dynamicDisabled"
        v-model:value="model[field]" 
        placeholder="请输入划线价"
        addon-after="元" 
        min="0" 
        :precision="1"
      />
    </template>

    <template #costPrice="{ model, field, schema }">
      <InputNumber 
        :disabled="schema.dynamicDisabled"
        v-model:value="model[field]" 
        placeholder="请输入成本价钱"
        addon-after="元" 
        min="0" 
        :precision="1"
      />
    </template>

    
    <template #singleSpecStock="{ model, field, schema }">
      <a-button v-if="!state.isUpdate" type="link" @click="handleOpenSingleSpecStock">管理初始化库存</a-button>
      <span v-else>{{ getSingleSpecStore }}</span>
      <MgtSkuStockModal @register="registerMgtSkuStockModal" @success="handleSingleSpecStock" />
    </template>

    <template #attribute="{ model, field }">
      <MyCardGroup :value="getSelectAttributeList" width="96%" style="margin-top: 10px;"
        :minCardNumber="0" addCardButtonName="添加属性" :isInitOne="false" 
        :defaultData="attributeCardDefaultData"
        delete-title="删除此属性将丢失本次编辑内容, 是否删除?" 
        @remove="handleRemoveAttribute">
        <template v-slot="{ data }">
          <SelectAttribute 
            :selectItem="data" 
            :attributeOptions="state.attributeOptions" 
            :is-update="state.isUpdate"  
            @change="handleSelectAttribute"
          />
        </template>
      </MyCardGroup>
    </template>

    <template #skuList="{ model, field }">
      <SkuStock :selectSpecList="state.specList" v-model:value="state.skuList" :isUpdate="state.isUpdate" ref="skuStockRef"/>
    </template>
  </BasicForm>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs, onMounted, watch, reactive, toRaw } from 'vue';
import { BasicForm, useForm  } from '/@/components/Form/index';
import { formSchema } from './goods.data';
import SelectSpec from './SelectSpec.vue';
import SelectAttribute from './SelectAttribute.vue';
import SkuStock from './SkuStock.vue';
import { InputNumber } from 'ant-design-vue';
import { useAdapt } from '/@/hooks/system/useAutoAdapt.ts';
import { useMessage } from '/@/hooks/web/useMessage';
import { listGoodsAttr } from "/@/api/bizShop/shop";
import { list as listGoodsCategory } from "../goodsCategory/category.api";
import MyCardGroup from '/@/components/Form/src/my/components/MyCardGroup.vue';
import { propTypes } from '/@/utils/propTypes';
import { toCompSelectSpecList } from './assembly';
import { isArray } from 'lodash';
import { GoodsState, GoodsProps } from './type';
import { useModal } from '/@/components/Modal';
import MgtSkuStockModal from './MgtSkuStockModal.vue';

const [registerMgtSkuStockModal, { openModal: openMgtSkuStockModal }] = useModal();
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const skuStockRef = ref<any>()
const attrs = useAttrs()
const state = reactive<any>({
  skuList: [],
  specList: [],

  isUpdate: false,
  detailContent: '',

  // 属性
  attributeOptions: [],
  // key: id
  selectAttributeMap: new Map(),

  // 单规格的sku信息
  singleSpecSku: {},
  singleSpecValue: undefined
})

const getSelectAttributeList = computed(() => Array.from(state.selectAttributeMap.values()))
const getSingleSpecStore = computed(() => state.singleSpecSku.stockList?.map(e => e.stock).reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0,
))

const specCardDefaultData = ref({
  specId: '',
  values: [],
  name: ''
})

const attributeCardDefaultData = ref({
  id: '',
  values: [],
  name: ''
})

const props = defineProps(GoodsProps)
const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelCol: {
    md: { span: 6 },
    sm: { span: 6 },
  },
  wrapperCol: {
    md: { span: 22 },
    sm: { span: 22 },
  },
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false
});

onMounted(async () => {
  const resp = await listGoodsAttr()
  state.attributeOptions = resp.map(e => ({
    label: e.name, value: e.id, ...e
  }))

})

watch(
  () => props.attributeList,
  (data: any) => {
    state.isUpdate = props.isUpdate;
    props.attributeList.forEach(e => state.selectAttributeMap.set(e.id, e))
  },
  { deep: true }
)

watch(
  () => props.specList,
  async (data: any) => {
    await resetFields()
    toCompSelectSpecList(props.specList).forEach(e => handleSelectSpec(e))
    handleSelectSpec([])

    state.skuList = props.skuList || []
    let formValue = {}
    if (!props.multiSpec && props.isUpdate) {
      state.singleSpecValue = state.skuList[0].specData[0].value
      state.singleSpecSku = state.skuList[0]
      formValue = { ...props, ...state.skuList[0]}
    } else {
      formValue = { ...props }
    }

    state.isUpdate = props.isUpdate;
    console.log("use data: ", props);

    if (state.isUpdate) {
      setFieldsValue({ ...props })
    }
    
    const treeData = await listGoodsCategory({})
    updateSchema([
      { field: 'categoryId', componentProps: { treeData } }
    ])
  },
  { deep: true }
)

//提交事件
async function getData() {
  try {
    console.log('state', state)
    const values = await validate()
    if (values.multiSpec) {
      state.skuList = skuStockRef.value.getSkuStock()
      return {
        ...values, 
        specList: unref(state.specList).map(e => {
          // 拷贝数据
          const newObj = JSON.parse(JSON.stringify(e))
          return {...newObj}
        }), 
        // 属性
        attributeList: Array.from(state.selectAttributeMap.values()),
        skuList: unref(state.skuList).map(e => { 
          delete e.tempId
          for (let key in e) {
            if (key.includes('sku_')) {
              delete e[key]
            }
          }
          return {
            ...e, 
            specData: e.specData
          }
        })
      };
    } else {
      state.singleSpecSku = {
        ...state.singleSpecSku,
        costPrice: values.costPrice,
        price: values.price,
        stockAlarm: values.stockAlarm,
        weight: values.weight,
        specData: [ { value: state.singleSpecValue }]
      }
      return {
        ...values, 
        specList: [ { values: [state.singleSpecValue] }],
        attributeList: Array.from(state.selectAttributeMap.values()),
        skuList: [ state.singleSpecSku ]
      }
    }
    
  } finally {
    
  }
}

const handleOpenSingleSpecStock = () => {
  openMgtSkuStockModal(true, { record: { tempId: '1', stockList: state.singleSpecSku.stockList }})
}

const handleSingleSpecStock = (tempId, value) => {
  state.singleSpecSku = { ...state.singleSpecSku, stockList: value }
  console.log('tempId', tempId, 'singleSpecSku', state.singleSpecSku)
  // emit('update:value', unref(skuData))
}

const handleRemoveCardGroup = (value) => {
  console.log('handleRemoveCardGroup', value);
  state.specList = state.specList.filter(e => e.specId !== value.specId)
}

const handleRemoveAttribute = (value) => {
  state.selectAttributeMap.delete(value.id)
}

const handleSelectSpec = (value) => {
  if (isArray(value)) {
    return
  }
  // 这里去重
  const tempMap = new Map()
  state.specList.forEach(e => { tempMap.set(e.specId, e) })
  tempMap.set(value.specId, value)

  state.specList = Array.from(tempMap.values()).filter(e => e.specId !== '')
  console.log('handleSelectSpec', state.specList);
} 

const handleSelectAttribute = (value) => {
  if (isArray(value)) {
    return
  }
  state.selectAttributeMap.set(value.id, value) 
} 

const handleBeforeAddSpec = () => {
  if (!state.skuList ||state.skuList.length == 0) {
    return true
  }
  // console.log('state.skuList', state.skuList)
  
  // const stockList = state.skuList?.flatMap(e => e.stockList).map(e => e.stock)
  // let totalStock = stockList && stockList.length > 0 ? stockList.reduce((e1, e2) => e1 + e2) : 0
  // if (totalStock > 0) {
  //   createMessage.error('需要商品所有规格的库存都为0时，才能添加规格。如需添加，请先调整库存')
  //   return false
  // }
  return true
}

const handleBeforeDeleteSpec = (spec) => {
  console.log('deletedSpec', spec);
  if (!state.skuList ||state.skuList.length == 0) {
    return true
  }
  
  // console.log('state.skuList', state.skuList)
  // let totalStock = state.skuList?.filter(e => spec.values.filter(e1 => e.specData.includes(e1)))
  //                 .flatMap(e => e.stockList).map(e => e.stock).reduce((e1, e2) => e1 + e2)
  // if (totalStock > 0) {
  //   createMessage.error('需要商品所有规格的库存都为0时，才能删除规格。如需添加，请先调整库存')
  //   return false
  // }
  return true
}

defineExpose({
  getData
})
</script>

<style lang="less">
.goods-spec-type {
  // display: flex;
}

</style>

